package com.example.myapplication1.ui.profile;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.example.myapplication1.R;
import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;

public class PersonalInfoFragment extends Fragment {
    private TextView usernameText;
    private TextView phoneNumberText;
    private TextView genderText;
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databaseHelper = new DatabaseHelper(requireContext());
        preferenceManager = new PreferenceManager(requireContext());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal_info, container, false);

        // 初始化视图
        usernameText = view.findViewById(R.id.username_text);
        phoneNumberText = view.findViewById(R.id.phone_number_text);
        genderText = view.findViewById(R.id.gender_text);
        ImageButton backButton = view.findViewById(R.id.back_button);

        // 设置返回按钮点击事件
        backButton.setOnClickListener(v -> {
            try {
                // 使用Navigation组件返回到个人中心
                Navigation.findNavController(view).navigate(R.id.action_personalInfo_to_profile);
            } catch (Exception e) {
                // 如果导航失败，回退到上一个Fragment
                requireActivity().getSupportFragmentManager().popBackStack();
            }
        });

        // 加载用户信息
        loadUserInfo();

        return view;
    }

    private void loadUserInfo() {
        // 从PreferenceManager获取用户名
        String username = preferenceManager.getUsername();
        usernameText.setText(username);

        // 从数据库获取用户信息
        long userId = preferenceManager.getUserId();
        String[] userInfo = databaseHelper.getUserInfo(userId);
        if (userInfo != null) {
            phoneNumberText.setText(userInfo[0]); // 手机号
            genderText.setText("male".equals(userInfo[1]) ? "男" : "女"); // 性别
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 